layui.config({
    base: "/layui/"
}).extend({
    index: 'lib/index'
}).use(['index', 'form', 'jquery', 'table'], function () {
    var form = layui.form,
        table = layui.table,
        admin = layui.admin;

    /**
     * 防重复设置
     * @type {boolean}
     */
    var edit_flag = true;

    table.render({
        elem: '#oem_user_info_table'
        , url: '/oem_user/queryData'
        , method: "post"
        , height: 500
        , limit: 50							//显示数目
        , limits: [50, 100]
        , cols: [[
            {field: 'id', title: 'ID', width: 80, sort: true, "align": "center",hide: true}
            , {field: 'userName', width: 200, title: '用户名', "align": "center"}
            , {field: 'trueName', width: 100, title: '真实名', "align": "center"}
            , {field: 'mobile', width: 130, title: '手机号', "align": "center"}
            , {
                field: 'type', width: 110, sort: true, title: '用户类型', "align": "center", templet: function (d) {
                    if (d.type == "AGENCY") {
                        return "代理商";
                    } else if (d.type == "ENTERPRISE") {
                        return "商家";
                    } else if (d.type == "OEM") {
                        return "服务商";
                    }else{
                        return "";
                    }
                }
            }
            , {field: 'levelId', width: 110, title: '代理商级别', "align": "center"}
            , {field: 'profitId', width: 120, title: '分润id', "align": "center"}
            , {field: 'recommendId', width: 130, title: '推荐人id', "align": "center", hide: true}
            , {field: 'agencyId', width: 130, title: '代理商id', "align": "center"}
            , {
                field: 'state', width: 130, title: '帐号状态', sort: true, "align": "center", templet: function (d) {
                    if (d.state == -1) {
                        return "锁定";
                    } else if (d.state == 0) {
                        return "过期";
                    } else if (d.state == 1) {
                        return "正常";
                    }else{
                        return "";
                    }
                }
            }
            , {field: 'remarks', width: 110, title: '备注', "align": "center"}
            , {field: 'createdTime', width: 200, title: '创建时间', "align": "center"}
            , {field: 'OPT', width: 250, title: '操作', "align": "center", toolbar: "#OptData"}
        ]]
        , request: {
            pageName: 'pageNo' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        where: {
            userName: $(".queryTable input[name='userName']").val(),
            type: $(".queryTable select[name='type']").val()
        }
        , id: 'oem_user_info_table'
        , page: true
    });

    /**
     * 用户操作
     */
    table.on('tool(oem_user_info_table)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        if (layEvent === 'del') { //删除
            layer.confirm('是否注销用户名为：' + data.userName + "的用户?", function (index) {
                //向服务端发送删除指令
                $.ajax({
                    url: '/oem_user/delete',
                    type: 'get',
                    data: {'id': data.id},//向服务端发送删除的id
                    success: function (suc) {
                        if (suc.message == "操作成功") {
                            obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                            layer.close(index);
                            layer.msg("注销成功", {icon: 1});
                        } else {
                            layer.msg("注销失败", {icon: 5});
                        }
                        table.reload('oem_user_info_table', {
                            where: {
                                userName: $(".queryTable input[name='userName']").val(),
                                type: $(".queryTable select[name='type']").val()
                            }
                        });
                    }
                });
                layer.close(index);
            });
        } else if (layEvent === 'state') { //恢复
            layer.confirm('是否恢复：' + data.userName + "的用户吗?", function (index) {
                //向服务端发送删除指令
                $.ajax({
                    url: '/oem_user/lock',
                    type: 'get',
                    data: {'id': data.id, 'state': 1, 'remarks': "恢复成功"},
                    success: function (suc) {
                        if (suc.message == "操作成功") {
                            layer.close(index);
                            layer.msg("恢复成功", {icon: 1});
                        } else {
                            layer.msg("恢复失败", {icon: 5});
                        }
                        table.reload('oem_user_info_table', {
                            where: {
                                userName: $(".queryTable input[name='userName']").val(),
                                type: $(".queryTable select[name='type']").val()
                            }
                        });
                    }
                });
                layer.close(index);
            });
        } else if (layEvent === 'change') {
            layer.open({
                type: 1,
                area: ['850px', '690px'],
                title: "商家变更",
                fixed: false, //不固定
                maxmin: true,
                maxmin: false,
                shadeClose: false,
                content: $('#user_win')
            });
            //表单值
            form.val("user_form", {
                "id": data.id,
                "type": data.type,
                "recommendId": data.recommendId
            });
            table.render({
                elem: '#department_result'
                , url: '/oem_user/agencyData'
                , method: 'post'
                , title: '代理商列表'
                , height: 500
                , limit: 50							//显示数目
                , limits: [50, 100]
                , cols: [[
                    {field: 'id', title: '用户编号', width: 100, "align": "center"}
                    , {field: 'userName', title: '用户名称', width: 180, "align": "center"}
                    , {field: 'mobile', title: '手机号码', width: 150, "align": "center"}
                    , {
                        field: 'type', width: 130, title: '用户类型', "align": "center", templet: function (d) {
                            if (d.type == "AGENCY") {
                                return "代理商";
                            }
                        }
                    }
                    , {field: 'recommendId', title: '代理商推荐人', width: 150, "align": "center",hide: true}
                    , {fixed: 'right', title: '操作', toolbar: '#hidden1-table-tool', width: 80}
                     //hide: true
                    ]]
                , request: {
                    pageName: 'pageNo' //页码的参数名称，默认：page
                    , limitName: 'pageSize' //每页数据量的参数名，默认：LIMIT
                },
                where: {
                    userName: $(".userTable input[name='userName']").val()
                }
                , id: 'department_result'
                , page: true
            });
        } else if (layEvent === 'edit') {
            layer.open({
                type: 1,
                area: ['500px', '400px'],
                title: "编辑",
                fixed: false, //不固定
                maxmin: true,
                maxmin: false,
                shadeClose: false,
                content: $('#edit_user_win')
            });
            form.val("edit_user_form", {
                "id": data.id,
                "userName": data.userName,
                "mobile": data.mobile
            });
        }
        ;
    });

    /**
     * 选择按钮
     */
    table.on('tool(department_result)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        var tr = obj.tr; //获得当前行 tr 的DOM对象
        var id = $("#id").val();  //被更换人id
        var type = $("#type").val();
        var queryRecommendId = data.recommendId; //选择修改的推荐人id
        if(id == queryRecommendId){
            layer.msg('当前用户是目标用户的父级，不能更改', {icon: 5});
            return;
        }
        if (layEvent === 'yes') { //转让确认
            layer.confirm("请确认", function (index) {
                $.ajax({
                    url: "/oem_user/modifyUserRecommend",
                    data: {recommendId: data.id, id: id, type: type},
                    type: "post",
                    success: function (result) {
                        if (result.message == "操作成功") {
                            layer.msg("更改成功", {
                                offset: '32%'
                                , icon: 1
                                , time: 0
                                , btn: '知道了'
                                , btnAlign: "c"
                                , shade: 0.4
                                , yes: function () {
                                    table.reload('oem_user_info_table', {
                                        where: {
                                            userName: $(".queryTable input[name='userName']").val()
                                        }
                                    });
                                    layer.closeAll();
                                }
                            })
                        } else {
                            layer.msg(result.message, {
                                offset: '32%'
                                , icon: 2
                                , time: 3000
                            }, function () {
                                layer.closeAll();
                            })
                        }
                    }
                });
            });
        }
    });

    /**
     * 编辑提交
     */
    form.on('submit(editOk)', function (data) {
        if (edit_flag) {
            edit_flag = false;
            $.ajax({
                url: "/oem_user/editUserInfo",
                data: data.field,
                type: "post",
                success: function (result) {
                    if (result.code == 1) {
                        edit_flag = true;
                        layer.msg("编辑成功", {
                            offset: '32%'
                            , icon: 1
                            , time: 0
                            , btn: '知道了'
                            , btnAlign: "c"
                            , shade: 0.4
                            , yes: function () {
                                table.reload('oem_user_info_table', {
                                    where: {
                                        userName: $(".queryTable input[name='userName']").val()
                                    }
                                });
                                layer.closeAll();
                            }
                        })
                    } else {
                        edit_flag = true;
                        layer.msg(result.message, {
                            offset: '32%'
                            , icon: 2
                            , time: 3000
                        }, function () {
                            layer.closeAll();
                        })
                    }

                }
            });
        } else {
            layer.msg("不能重复提交表单", {
                offset: '32%'
                , icon: 2
                , time: 3000
            }, function () {

            })
        }

        return false;
    });

    $(".search_btn").click(function () {

        table.reload('oem_user_info_table', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                userName: $(".queryTable input[name='userName']").val(),
                type: $(".queryTable select[name='type']").val()
            }
        });
    });

    $(".agency_btn").click(function () {

        table.reload('department_result', {
            page: {
                curr: 1 //重新从第 1 页开始
            }
            , where: {
                userName: $(".userTable input[name='agencyName']").val()
            }
        });
    });
});



